package cn.zshprint.serein.service.impl;

import cn.zshprint.serein.entity.PermissionRoleRelation;
import cn.zshprint.serein.entity.RoleUserRelation;
import cn.zshprint.serein.entity.User;
import cn.zshprint.serein.service.PermissionRoleRelationService;
import cn.zshprint.serein.service.RoleUserRelationService;
import cn.zshprint.serein.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zshprint.serein.entity.Permission;
import cn.zshprint.serein.service.PermissionService;
import cn.zshprint.serein.mapper.PermissionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
@Slf4j
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService {

    @Resource
    private RoleUserRelationService roleUserRelationService;
    @Resource
    private PermissionRoleRelationService permissionRoleRelationService;
    @Resource
    private UserService userService;

    @Override
    public Permission selectOne(Integer id) {
        return getById(id);
    }

    @Override
    public List<Permission> selectAll() {
        return list();
    }

    @Override
    public List<Permission> selectByUser(String username) {
        User user = userService.getOne(new QueryWrapper<User>()
                .eq("username", username));
        Integer id = user.getId();
        List<Integer> roleIds = new ArrayList<>();
        roleUserRelationService.list(new QueryWrapper<RoleUserRelation>()
                .eq("user_id", id))
                .stream()
                .forEach(item ->{
                    roleIds.add(item.getRoleId());
                });
        log.info("roleIds是{}",roleIds);
        List<Integer> permissionIds = new ArrayList<>();
        permissionRoleRelationService.list(new QueryWrapper<PermissionRoleRelation>()
                .in("role_id", roleIds))
                .forEach(item->{
                    permissionIds.add(item.getPermissionId());
                });
        return list(new QueryWrapper<Permission>()
                .eq("status", 1)
                .in("permission_id", permissionIds));
    }

    @Override
    public Integer saveOne(String description) {
        Permission permission = new Permission();
        permission.setDesc(description);
        permission.setCreateTime(LocalDateTime.now());
        save(permission);
        return permission.getId();
    }

    @Override
    public Integer deleteOne(Integer id) {
        Permission permission = getById(id);
        permission.setStatus(0);
        updateById(permission);
        return id;
    }
}




